package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 菜品管理
 */
@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 新增菜品
     * @param dishDto
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto){

        //输出日志
        log.info(dishDto.toString());

        dishService.saveWithFlavor(dishDto);

        //清理新增菜品后的缓存
        String key = "dish_" + dishDto.getCategoryId() + "_" + dishDto.getStatus();
        redisTemplate.delete(key);

        return R.success("新增菜品成功");
    }

    /**
     * 菜品分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page,int pageSize,String name){

        //构造分页构造器
        Page<Dish> pageInfo = new Page<>(page,pageSize);
        Page<DishDto> dishDtoPage = new Page<>();

        //条件构造器
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(name != null,Dish::getName,name);
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

        //分页查询
        dishService.page(pageInfo,queryWrapper);

        //对象拷贝,且忽略掉页面当中显示的内容，因为我们要处理菜品分类这个字段。(这里的拷贝的属性是pageInfo当中的属性)
        BeanUtils.copyProperties(pageInfo,dishDtoPage,"records");
        List<Dish> records = pageInfo.getRecords();
        List<DishDto> list = new ArrayList<>();
        for (Dish record : records) {
            DishDto dishDto = new DishDto();
            //因为重新创建了DishDto对象，所以需要重新拷贝其他的属性。(这里的拷贝的属性是Dish当中的属性)
            BeanUtils.copyProperties(record,dishDto);

            Long categoryId = record.getCategoryId();//拿到分类的id
            Category category = categoryService.getById(categoryId);//根据id来查询分类对象
            if (category != null){
                String categoryName = category.getName();//获取分类名称
                dishDto.setCategoryName(categoryName);//给菜品分类字段进行赋值
                list.add(dishDto);
            }
        }
        dishDtoPage.setRecords(list);
        return R.success(dishDtoPage);
    }

    /**
     * 根据id查询菜品信息和对应的口味信息，用于回显
     * 注意：菜品分类字段前端已经做好了，我们不管
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> get(@PathVariable("id") Long id){

        DishDto byIdWithFlavor = dishService.getByIdWithFlavor(id);
        return R.success(byIdWithFlavor);
    }

    /**
     * 修改菜品
     * @param dishDto
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto){

        dishService.updateWithFlavor(dishDto);

        //清理修改分类后的缓存
        String key = "dish_" + dishDto.getCategoryId() + "_" + dishDto.getStatus();
        redisTemplate.delete(key);

        return R.success("成功");
    }

    /**
     * 根据dishId来批量启售、停售
     * 注意点：用集合类型的形参接收前端参数时，一定要加@RequestParam注解，并绑定相应的参数
     * @return
     */
    @PostMapping("/status/{status}")
    public R<String> upDateStatus(@PathVariable("status") Integer status, @RequestParam("ids") List<Long> ids){
        List<Dish> collection = new ArrayList<>();
        for (Long id : ids) {
            Dish dish = new Dish();
            dish.setId(id);
            dish.setStatus(status);
            collection.add(dish);
        }
        dishService.updateBatchById(collection);

        //根据dishId来查询categoryId，并清理缓存
        for (Long id : ids) {
            Dish dish = dishService.getById(id);
            Long categoryId = dish.getCategoryId();
            String key = "dish_" + categoryId + "_1" ;
            redisTemplate.delete(key);
        }


        return R.success("修改成功");
    }

    /**
     * 根据id来批量删除,在删除菜品时，
     * 1.对于状态为售卖中的商品不能删除
     * 2.要把菜品表所关联的`dish——flavor`表当中的相应信息进行删除
     * 注意点：用集合类型的形参接收前端参数时，一定要加@RequestParam注解，并绑定相应的参数
     * @param ids
     * @return
     */
    @DeleteMapping()
    public R<String> delIds(@RequestParam("ids") List<Long> ids){
        dishService.removeWithFlavor(ids);
        return R.success("删除成功！！");
    }

    /**
     * 根据条件查询对应的菜品数据,并且为了实现移动端前台的菜品展示相应功能，
     * 需要查询对应菜品下的对应口味。
     * @param dish
     * @return
     */
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish){

        //动态构造key
        String key = "dish_" + dish.getCategoryId() + "_" + dish.getStatus();

        //先从redis中获取缓存数据
        ValueOperations valueOperations = redisTemplate.opsForValue();
        List<DishDto> dtoList = (List<DishDto>) valueOperations.get(key);

        if (dtoList != null) {
            //如果存在，则直接返回，无需查询数据库
            return R.success(dtoList);
        }
        //如果不存在，则查询数据库

        //构造查询条件
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dish.getCategoryId() != null,Dish::getCategoryId,dish.getCategoryId());
        //查询启售的
        queryWrapper.eq(Dish::getStatus,1);
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        //根据category_id查询对应的dish
        List<Dish> list = dishService.list(queryWrapper);
        List<DishDto> dtoList1 = new ArrayList<>();
        for (Dish dish1 : list) {
            //进行属性的拷贝
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(dish1,dishDto);
            //通过dish_id来查询对应的dish_flavor
            Long id = dish1.getId();
            LambdaQueryWrapper<DishFlavor> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(DishFlavor::getDishId,id);
            List<DishFlavor> dishFlavors = dishFlavorService.list(queryWrapper1);
            //给dishDto中的flavor属性进行赋值
            dishDto.setFlavors(dishFlavors);
            //将dishDto加入到dtoList当中
            dtoList1.add(dishDto);
        }
        //将查询到的菜品数据缓存到redis中
        ValueOperations valueOperations1 = redisTemplate.opsForValue();
        valueOperations1.set(key,dtoList1,60, TimeUnit.MINUTES);

        return R.success(dtoList1);
    }
}
